package com.qf58.search.utils;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: zhubo
 * Date: 2017-08-29
 * Time: 15:56
 */
public class JsonUtils {

    /**
     * 获取简单json字符串中指定的属性
     * @param json
     * @param name
     * @return
     * @throws IOException
     */
    public static Object getValue(String json , String name) throws IOException{

        Gson gson = new Gson();
        Map<String,Object> map = gson.fromJson(json,new TypeToken<HashMap<String,Object>>(){}.getType());
        Object returnVal = map.get(name);
        return returnVal;
    }

    /**
     * 获取对象对应的json字符串 去除null值
     * @param obj
     * @return
     * @throws IOException
     */
    public static String obj2Str(Object obj)throws IOException{
        Gson gson = new Gson();
        String jsonStr = gson.toJson(obj);
        return jsonStr;
    }

    public static String jsonSkipField(String jsonStr , String[] str){
        Gson gson = GsonUtils.getDoubleConvertGson();
        Map<String,Object> map = gson.fromJson(jsonStr,new TypeToken<HashMap<String,Object>>(){}.getType());
        Set<String> set = map.keySet();
        for (String s : str ) {
            if(set.contains(s)){
                map.remove(s);
            }
        }

        return gson.toJson(map);
    }

    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",1231231231);
        map.put("labelIds",new Integer[]{1,2,3,4,5,6});

        String gson = new Gson().toJson(map);
        System.out.println(gson);

        System.out.println(jsonSkipField(gson,new String[]{"ids"}));
    }

}
